<template>
  <div class="page-login">
    <el-form
      ref="form"
      :model="model"
      :rules="rules"
      label-width="60"
      hide-required-asterisk
    >
      <el-form-item label="用户名" prop="username">
        <el-input v-model="model.username" />
      </el-form-item>

      <el-form-item label="密码" prop="password">
        <el-input v-model="model.password" type="password" />
      </el-form-item>

      <el-form-item label="验证码" prop="verifyCode">
        <el-space>
          <el-input v-model="model.verifyCode" @keyup.enter="handleLogin" />
          <Captcha ref="captchaRef" v-model="model.captchaId" />
        </el-space>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" :loading="loading" @click="handleLogin">
          Login
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import Captcha from "./components/captcha/index.vue";
import { loginAPI } from "@/api/login.js";

export default {
  name: "Login",

  components: {
    Captcha,
  },

  data() {
    return {
      // 表单数据对象
      model: {
        username: "admin",
        password: "123456",
        captchaId: "", // 验证码id
        verifyCode: "",
      },
      // 表单校验规则
      rules: {
        username: [{ required: true, message: "Username 必须" }],
        password: [{ required: true, message: "Password 必须" }],
        verifyCode: [{ required: true, message: "VerifyCode 必须" }],
      },
      loading: false, // 用于表示当前是否请求中
    };
  },

  methods: {
    /**
     * 处理登录
     */
    async handleLogin() {
      // if (this.loading) return;

      // 1. 手动表单校验，回调函数，回调函数的参数是一个boolean
      //                Promise
      await this.$refs.form.validate();

      try {
        // 2. 校验成功，直接去登录
        //    设置 loading 为 true
        this.loading = true;
        const result = await loginAPI(this.model);

        // 3. 登录成功
        // alert("登录成功");
        this.$message.success("登录成功");

        // 4. 将 result.token 写入到 vuex 中
        this.$store.commit("user/setToken", result.token);

        // 5. 跳转回之前要去的页面
        const redirect = this.$route.query.redirect || "/";
        this.$router.replace(redirect);
      } catch (error) {
        // 登录失败，刷新验证码
        this.$refs.captchaRef.refresh();
        this.model.verifyCode = "";
        this.loading = false;
      }

      // this.$refs.form
      //   .validate()
      //   .then(() => {
      //     console.log("校验成功");

      //     return loginAPI(this.model);
      //   })
      //   .then(() => {
      //     console.log("登录成功");
      //   })
      //   .catch(() => {
      //     console.log("校验失败");
      //   });
    },
  },
};
</script>

<style scoped>
.page-login {
  height: 100%;
  background-color: #ccc;
  overflow: hidden;
}

.el-form {
  margin: 50px auto;
  padding: 16px;
  width: 360px;
  border-radius: 10px;
  background-color: #fff;
}
</style>
